package com.atguigu.guli.gateway.config;

import com.atguigu.guli.gateway.execept.GoldException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.stream.Collectors;

@Configuration
public class GateConfig {
    //将自定义异常处理器对象注入到容器中
    @Bean
    @Order(-1)
    public GoldException jsonExceptionHandler(ErrorAttributes errorAttributes,
                                              org.springframework.boot.autoconfigure.web.ResourceProperties resourceProperties,
                                              ServerProperties serverProperties,
                                              ObjectProvider<ViewResolver> viewResolvers,
                                              ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext){

        GoldException handler = new GoldException(errorAttributes, resourceProperties,
                serverProperties.getError(), applicationContext);
        handler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
        handler.setMessageWriters(serverCodecConfigurer.getWriters());
        handler.setMessageReaders(serverCodecConfigurer.getReaders());
        return handler;
    }

    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedHeader("*");  //允许所有头跨域
        configuration.addAllowedMethod("*"); //允许所有方法跨域;
        configuration.addAllowedOrigin("*");  //允许所有服务器跨域
        configuration.setAllowCredentials(true); //允许携带cookie跨域

        //可以让所有的跨域访问
        source.registerCorsConfiguration("/**", configuration);
        return new CorsWebFilter(source);
    }
}
